from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.utils import jwt_decode_handler
from new_app.models import *
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from new_pro.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入序列化类
from .myser import *

#导入中间件
from django.utils.deprecation import MiddlewareMixin
# 阿里云短信服务
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
#建立redis链接
#定义ip
# host = '192.168.1.103'
host = '127.0.0.1'

#建立服务连接
r = redis.Redis(host=host)

class MyCode(View):
    
    # 定义随即验证颜色
    def ger_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        
        return (R, G, B)
    # 随机验证码
    def get(self, request):
        # 画布
        img_size = (110, 50)
        # 定义颜色
        image = Image.new('RGB', img_size, 'white')
        # 为这张画布定义画笔对象
        draw = ImageDraw.Draw(image, 'RGB')
        # 定义随即字符串
        source = '0123456789'
        # 定义容器接受随机字符串
        code_str = ''
        for i in range(4):
            # 获取字体颜色
            text_color = self.ger_random_color()
            # 获取字符串
            tmp_num = random.randrange(len(source))
            # 获取字符集
            random_str = source[tmp_num]
            # 添加到容器中
            code_str += random_str
            # 绘制
            draw.text((10+30*i,20), random_str, text_color)
        # 文件流缓冲区
        buf = io.BytesIO()
        # 将图片保存到缓冲区
        image.save(buf, 'png')
        # 将随机验证码存储到redis中
        r.set('code', code_str)
        # 将随机验证码存储到session中
        request.session['code'] = code_str
        # print(request.session.get('code'))
        return HttpResponse(buf.getvalue(), 'image/png')

# 手写md5加密方法
def make_password(mypass):
    #生成md5对象
    md5 = hashlib.md5()
    # 定义加密对象
    sign_str = mypass
    # 转码
    sign_utf8 = str(sign_str).encode(encoding='utf-8')
    # 加密操作
    md5.update(sign_utf8)
    # 生成密文
    md5_server = md5.hexdigest()
    # 返回最终数据
    return md5_server


# 生成随机验证码
def get_random_str():
    # 验证码是由 字母a~z  A~Z 数字 0~9 组成
    # 在 ascii 码中 小写a的起点是97 大写A起点是65
    a_ = [chr(var) for var in range(97, 123)]  # 小写a的列表推导式
    A_ = [chr(var) for var in range(65, 91)]  # 大写A的列表推导式
    num_ = [str(var) for var in range(0, 9)]  # 数字的
    # 使用sample 在列表中随机生成6个任意字母数字
    return ''.join(random.sample(a_ + A_ + num_, 6))


class LognIn(APIView):
    def get(self, request):
        # 获取账户名和密码
        login_type = request.GET.get('type')
        if login_type == 'pwd':
            # 账号密码登录
            username = request.GET.get('username')
            password = request.GET.get('password')
            code = request.GET.get('code')
            mycode = r.get('code').decode('utf-8')
            if code != mycode:
                res = {}
                res['code'] = 406
                res['message'] = '验证码错误'
                return Response(res)
            user = User.objects.filter(username=username,password=make_password(password)).first()
            if user:
                # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
                # payload = jwt_payload_handler(user)
                # token = jwt_encode_handler(payload)

                res = {}
                res['code'] = 200
                res['message'] = '登陆成功'
                res['username'] = username
                res['uid'] = user.id
                res['pid'] = user.pid
                # res['jwt'] = token
                
                return Response(res)
            res = {}
            res['code'] = 405
            res['message'] = '账号或密码错误,请重新输入!'
            return Response(res)
        else:
            phone = request.GET.get('phone')
            print(phone)
            code = request.GET.get('code')
            print(code)
            my_code = r.get('phone').decode('utf-8')
            print(my_code)
            if code != my_code:
                res = {}
                res['code'] = 406
                res['message'] = '验证码错误'
                return Response(res)
            user = User.objects.filter(phone=phone).first()
            if user:
                # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
                # payload = jwt_payload_handler(user)
                # token = jwt_encode_handler(payload)
                res = {}
                res['code'] = 200
                res['message'] = '登陆成功'
                res['username'] = user.username
                res['uid'] = user.id
                res['pid'] = user.pid
                # res['jwt'] = token
            else:
                user = User(
                    username='游客' + str(code),
                    password=make_password(000000),
                    phone=phone
                )
                user.save()
                user = User.objects.filter(phone=phone).first()
                res = {}
                res['code'] = 201
                res['message'] = '手机号注册成功'
                res['username'] = user.username
                res['uid'] = user.id
                res['pid'] = user.pid
            return Response(res)





class PhoneCode(APIView):
    def post(self, request):
        # 手机号登录,顺便判断是否已经注册,未注册则自动注册并登录
        phone = request.data.get('phone')  # 接收到用户发来的验证码
        
        res = {}
        token = r.get(phone)
        # token = '123456'

        if token:  # 去redis 中查看 是否这个手机号
            res['code'] = 401
            res['message'] = "请一分钟后再次发送"
            return JsonResponse(res)


        else:
            token = get_random_str()  # 生成验证码
            AK = "LTAI4G8cL1SrbrHSrnZn42Hp"
            SK = "HHJeGvx1qd3v5dOCb6Y2JoIyUF8HuQ"

            # 登录阿里云客户端
            client = AcsClient(AK, SK, 'cn-hangzhou')

            request = CommonRequest()
            request.set_accept_format('json')
            request.set_domain('dysmsapi.aliyuncs.com')
            request.set_method('POST')
            request.set_protocol_type('https')  # https | http
            request.set_version('2017-05-25')
            request.set_action_name('SendSms')

            request.add_query_param('RegionId', "cn-hangzhou")
            # 这个手机号可以从前端获取
            request.add_query_param('PhoneNumbers', str(phone))
            request.add_query_param('SignName', "秒秒测")
            request.add_query_param('TemplateCode', "SMS_190785473")
            # 验证码可以随机获取
            request.add_query_param('TemplateParam', str({'code': token}))
            r.set('phone', token)  # 存储到redis
            # 设置访问周期为60秒
            r.expire(phone, 60)

            response = client.do_action(request)
            print(str(response, encoding='utf-8'))
            res['code'] = 200
            res['message'] = "验证码已发送"
            # res['token'] = phone
            return JsonResponse(res)
# 注册
class Register(APIView):
    
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', '未收到用户名')
        password = request.GET.get('password1', '未收到密码')
        apply = request.GET.get('apply', '未收到权限码')
        print(password)
        code = request.GET.get('code', '未收到验证码')
        # 从redis获取生成好的验证码
        mycode = r.get('code').decode('utf-8')
        # 从session获取验证码
        # mycode1 = request.session.get('code', None)
        if code != mycode:
            res = {}
            res['code'] = 405
            res['message'] = '验证码错误'
            return Response(res)
        # 判断有没有重名用户
        user = User.objects.filter(username=username).first()
        if user:
            # 该用户已存在
            res = {}
            res['code'] = 405
            res['message'] = '用户已经存在'
            return Response(res)
        # 进行数据入库
        
        if apply:
            user = User(
                username=username,
                password=make_password(password),
                pid=int(apply)
            )
        else:
            user = User(
                username=username,
                password=make_password(password),
            )
        user.save()
        user = User.objects.filter(username=username).first()
        print(user)
        # 返回结果
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        res['username'] = username
        res['uid'] = user.id
        res['pid'] = user.pid
        return Response(res)

class CityCode(APIView):
    def get(self, request):
        with open('static/city_code.json', encoding='utf-8') as f:
            json_list = json.load(f)
            # province_list = []
            # city_list = []
            # county_list = []
            # for province in json_list:
            #     province_list.append({'name': province['name'],'code': province['code']})
            #     for city in province['city']:
            #         city_list.append({'name': city['name'], 'code': city['code']})
            #         for county in city['area']:
            #             county_list.append({'name': county['name'], county['code']})

        res = {}
        res['code'] = 200
        res['message'] = '获取成功'
        res['json_list'] = json_list
        return Response(res)
from django.core.serializers import serialize
class UserMsg(APIView):
    def get(self, request):
        uid = request.GET.get('uid')
        print(uid)
        user = User.objects.filter(id=int(uid)).first()
        user_list = UserSerializer(user).data
        # user_list.is_valid()
        # print(user_list.data)
        print(user_list)
        res = {}
        res['code'] = 200
        res['message'] = '请求成功'
        res['user'] = user_list
        return Response(res)


class UpdateUser(APIView):
    def get(self, request):
        uid = request.GET.get('uid', None)
        username = request.GET.get('username', None)
        email = request.GET.get('email', None)
        phone = request.GET.get('phone', None)
        address = request.GET.get('address', None)
        company = request.GET.get('company', None)
        print(uid,username,email,phone,address)

        user = User.objects.filter(id=uid).first()
        if user:
            user.name = username
            user.email = email
            user.phone = phone
            user.company_id = company
            user.save()
        useraddress = UserAddress.objects.filter(uid=int(uid),address_dedfault=1).first()
        if useraddress:
            useraddress.address_dedfault = 0
            useraddress.save()
        UserAddress(address=address,uid=int(uid),address_dedfault=1).save()
        res = {}
        res['code'] = 200
        res['message'] = '请求成功'
        return Response(res)


class UpdateApply(APIView):
    def get(self, request):
        user = request.GET.get('user')
        apply = request.GET.get('apply')
        ApplyInfo(user=user, apply=apply).save()
        res = {}
        res['code'] = 200
        res['message'] = '申请成功,请等待审批'
        return Response(res)

class UserList(APIView):
    def get(self, request):
        uid = request.GET.get('uid',None)
        pid = request.GET.get('pid',None)
        if pid == '1':
            user = User.objects.filter(id=uid)
            user_list = UserSerializer(user, many=True).data
        else:
            users = User.objects.all()
            user_list = UserSerializer(users, many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '用户列表获取成功'
        res['user_list'] = user_list
        return Response(res)

# 获取申请列表
class ApplyList(APIView):
    def get(self, request):
        applys = ApplyInfo.objects.all()
        applys_list = ApplyInfoSerializer(applys, many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '数据获取成功'
        res['apply_list'] = applys_list
        return Response(res)
# 修改申请
class UpdateApplys(APIView):
    def get(self, request):
        aid = request.GET.get('id')
        user = request.GET.get('user')
        apply = request.GET.get('apply')
        is_delete = request.GET.get('is_delete')
        user_apply = ApplyInfo.objects.filter(id=aid).first()
        user_apply.is_delete = is_delete
        user_apply.save()
        res = {}
        if is_delete == '1':
            users = User.objects.filter(username=user).first()
            users.pid = apply
            users.save()
            res['code'] = 200
            res['message'] = '操作成功,申请通过'
        else:
            res['code'] = 200
            res['message'] = '操作成功,申请未通过'
        return Response(res)

# 创建客户表
class CreateCustomer(APIView):
    def get(self, request):
        '''
        'username'  用户名
        'contacts'  联系人
        'phone'     电话
        'address'   收件地址
        '''
        username = request.GET.get('username')
        contacts = request.GET.get('contacts')
        phone = request.GET.get('phone')
        address = request.GET.get('address')
        Customers(username=username,contacts=contacts,phone=phone,address=address).save()
        res = {}
        res['code'] = 200
        res['message'] = '创建成功'

        return Response(res)
# 创建公司
class CreateCompany(APIView):
    def get(self, request):
        '''
        username  
        address
        '''
        username = request.GET.get('username')
        address = request.GET.get('address')
        print(username, address)
        Companys(name=username,address=address).save()
        res = {}
        res['code'] = 200
        res['message'] = '创建成功'


        return Response(res)
# 获取公司列表
class CompanyList(APIView):
    def get(self, request):
        companys = Companys.objects.all()
        company_list = CompanysSerializer(companys,many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '数据请求成功'
        res['company_list'] = company_list
        return Response(res)

class CustomerList(APIView):
    def get(self, request):
        customers = Customers.objects.all()
        customer_list = CustomersSerializer(customers, many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '数据获取成功'
        res['customer_list'] = customer_list
        return Response(res)


class OrderList(APIView):
    def get(self, request):
        orders = Orders.objects.all()
        order_list = OrdersSerializer(orders, many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '数据获取成功'
        res['order_list'] = order_list
        return Response(res)


def jwt_response_payload_handler(token, user=None, request=None):
    '''
    :param token: jwt生成的token值
    :param user: User对象
    :param request: 请求
    '''
    print('*' * 100)
    return {
        'token': token,
        'user': user.id,
        # 'user': UserSerializer(user, context={'request': request}).data
        # 'userid': user.id,
        # 'userphone':user.phone
    }


class GoodsTypeAdd(APIView):
    def get(self, request):
        '''
        goods_type_name: 货物类型名称,
        equipment: 设备类型,
        ping_num: 延迟开始时间,
        interval: 记录间隔,
        goods_type_desc: 货物类型描述,
        // 理想温度范围
        min_temperature: 最低温度,
        max_temperature: 最高温度,
        alert_data: {
            // 内容包括: 
            // temperature    单温度
            // temperature_min,temperature_max    多温度
            // alert_type    选中的类型(上限,下限,多温度)
            // threshold    阈值的数值
            // threshold_type    阈值的类型(1 分钟,2 小时,3 天)
            'alert_checked_1':{'choice':true,'temperature': '','temperature_min': '','temperature_max': '','alert_type': '', 'threshold': '', 'threshold_type': ''},
            'alert_checked_2':{'choice':false,'temperature': '','temperature_min': '','temperature_max': '','alert_type': '', 'threshold': '', 'threshold_type': ''},
            'alert_checked_4':{'choice':false,'temperature': '','temperature_min': '','temperature_max': '','alert_type': '', 'threshold': '', 'threshold_type': ''},
            'alert_checked_5':{'choice':false,'temperature': '','temperature_min': '','temperature_max': '','alert_type': '', 'threshold': '', 'threshold_type': ''},
            'alert_checked_3':{'choice':false,'temperature': '','temperature_min': '','temperature_max': '','alert_type': '', 'threshold': '', 'threshold_type': ''},
            'alert_checked_6':{'choice':false,'temperature': '','temperature_min': '','temperature_max': '','alert_type': '', 'threshold': '', 'threshold_type': ''},
        },
        '''

        '''
        货物类型表字段
        name = 货物类型名称
        delayed = 延迟开始
        interval = 记录间隔
        min_temperature = 最低温度
        max_temperature = 最高温度
        alert = 报警事件
        desc = 描述
        equipment_id = 设备类型
        '''
        '''
        报警事件表字段
        alert_class = 报警事件类型(alert_type)
        temperature = 温度范围 {'temperature_min': '','temperature_max': ''} or {'temperature':''}
        threshold = 阈值(threshold,根据threshold_type进行对应的换算,数据库存储单位为分钟,小时*60,天*1440)
        '''
        '''
        设备类型表
        '''
        '''
        前端传递参数:
        'goods_type_name': this.goods_type_name,
        'equipment': this.equipment,
        'ping_num': this.ping_num,
        'interval': this.interval,
        'goods_type_desc': this.goods_type_desc,
        'min_temperature': this.min_temperature,
        'max_temperature': this.max_temperature,
        'alert_data': alert_data_list
        '''
        # print(request.GET.getlist('alert_data[]'))
        goods_type_name = request.GET.get('goods_type_name')
        equipment = request.GET.get('equipment')
        ping_num = request.GET.get('ping_num')
        interval = request.GET.get('interval')
        goods_type_desc = request.GET.get('goods_type_desc')
        min_temperature = request.GET.get('min_temperature')
        max_temperature = request.GET.get('max_temperature')
        alert_data = request.GET.getlist('alert_data[]')

        if goods_type_name and equipment and ping_num and interval and goods_type_desc and min_temperature and max_temperature and alert_data:
            # 将报警事件存储起来
            alert_id_list = []
            for item in alert_data:
                item = json.loads(item)
                alert_class = item['alert_type']
                if item['temperature']:
                    temperature = str(item['temperature'])
                else:
                    temperature = json.dumps([item['temperature_min'], item['temperature_max']], ensure_ascii=False)
                if item['threshold_type'] == '3':
                    threshold = item['threshold'] * 1440
                elif item['threshold_type'] == '2':
                    threshold = item['threshold'] * 60
                else:
                    threshold = item['threshold']
                alertevent = AlertEvents()
                alertevent.alert_class = alert_class
                alertevent.temperature = temperature
                alertevent.threshold = threshold
                alertevent.save()
                alert_id_list.append(AlertEvents.objects.filter(
                    alert_class=alert_class,
                    temperature=temperature,
                    threshold=threshold
                        ).first().id)
            goodstype = GoodsTypes()
            goodstype.name = goods_type_name
            goodstype.delayed = ping_num
            goodstype.interval = interval
            goodstype.min_temperature = min_temperature
            goodstype.max_temperature = max_temperature
            goodstype.alert = json.dumps(alert_id_list, ensure_ascii=False)
            goodstype.desc = goods_type_desc
            goodstype.equipment_id = equipment
            goodstype.save()
            res = {}
            res['code'] = 200
            res['message'] = '创建成功'
            return Response(res)
        res = {}
        res['code'] = 400
        res['message'] = '创建失败,请重现创建'
        return Response(res)
class GetGoodsTypesList(APIView):
    def get(self, request):
        goods_type_list = GoodsTypesSerializer(GoodsTypes.objects.all(),many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '获取成功'
        res['goods_type_list'] = goods_type_list
        return Response(res)

class CreateEquipment(APIView):
    def get(self, request):
        equipment_name = request.GET.get('name')
        equipment = Equipments()
        equipment.equipment_name = equipment_name
        equipment.save()
        res = {}
        res['code'] = 200
        res['message'] = '创建成功'
        return Response(res)
class GetEquipmentList(APIView):
    def get(self, request):
        equipments = Equipments.objects.all()
        equipment_list = EquipmentsSerializer(equipments, many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '获取成功'
        res['equipment_list'] = equipment_list
        return Response(res)


class CreateTags(APIView):
    def get(self, request):
        '''
        tag_number
        goods_type
        user
        '''
        tag_number = request.GET.get('tag_number')
        goods_type = request.GET.get('goods_type')
        user = request.GET.get('user')
        uid = request.GET.get('uid')
        label = Labels()
        label.label_id = tag_number
        label.goods_type = goods_type
        label.use_user = user
        label.create_user = uid
        label.save()
        res = {}
        res['code'] = 200
        res['message'] = '创建成功'
        return Response(res)

class TagsList(APIView):
    def get(self, request):
        label_list = LabelsSerializer(Labels.objects.all(), many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '获取成功'
        res['label_list'] = label_list
        return Response(res)

class CreateOrder(APIView):
    def get(self, request):
        # order_number:this.order_number,
        invoice = request.GET.get('order_number')
        # username:username,
        username = request.GET.get('username')
        # contacts:contacts,
        contacts = request.GET.get('contacts')
        # phone:phone,
        phone = request.GET.get('phone')
        # address:address,
        address = request.GET.get('address')
        # goods_type_name:goods_type_name,
        goods_type_name = request.GET.get('goods_type_name')
        # delayed:delayed,
        delayed = request.GET.get('delayed')
        # interval:interval,
        interval = request.GET.get('interval')
        # safe_temperature:safe_temperature,
        safe_temperature = request.GET.get('safe_temperature')
        # alert:alert,
        alert = request.GET.get('alert')
        # order_state:order_state,
        order_state = request.GET.get('order_state')
        # temperature_record:temperature_record,
        temperature_record = request.GET.get('temperature_record')
        order = Orders()
        res = {}
        if order:
            order.invoice = invoice
            order.username=username
            order.contacts=contacts
            order.phone=phone
            order.address=address
            order.goods_type_name=goods_type_name
            order.delayed=delayed
            order.interval=interval
            order.safe_temperature=safe_temperature
            order.alert=alert
            order.order_state=order_state
            order.temperature_record=temperature_record
            order.save()
            res['code'] = 200
            res['message'] = '创建成功'
        else:
            res['code'] = 301
            res['message'] = '创建失败'
        return Response(res)


class TemperatureList(APIView):
    def get(self, request):
        oid = request.GET.get('id')
        print(type(oid))
        temperature_data = Temperatures.objects.filter(order_ID=oid)
        print(temperature_data)

        temperature_list = TemperaturesSerializer(temperature_data, many=True).data
        res = {}
        res['code'] = 200
        res['message'] = '获取成功'
        res['temperature_list'] = temperature_list
        return Response(res)

class TemperatureAdd(APIView):
    def get(self, request):
        oid = request.GET.get('id')
        order = Orders.objects.filter(id=oid).first()
        safe_temperature = [int(x) for x in order.safe_temperature.split('~')]
        for i in ['运输中', '已签收']:
            order.order_state = i
            for j in range(100):
                if i == '运输中':
                    temperature = random.randint(10,50)
                    if safe_temperature[0]>temperature or safe_temperature[1]<temperature:
                        order.order_state = '报警'
                        alert = 1
                        break
                    Temperatures(order_ID=order.invoice,temperature_new=temperature).save()
            if alert:
                break

        res = {}
        res['code'] = 200
        res['message'] = '发货成功'
        res['order_state'] = order.order_state
        return Response(res)

        